<?php


namespace app\lib;

use app\Code;
use app\lib\exception\AuthException;
use app\lib\exception\ConfigurationException;
use app\lib\exception\OutsideApiException;
use app\lib\exception\ParamException;
use app\lib\exception\ServiceException;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\RouteNotFoundException;
use Throwable;
use think\exception\Handle;
use think\exception\HttpException;
use think\exception\ValidateException;
use think\Response;


class Http extends Handle
{
    protected function returnJson($msg, $code, $httpCode = 200){
        return Response::create([
            'msg' => $msg,
            'code' => $code,
            'data' => [],
        ], 'json', $httpCode);
    }

    public function render($request, Throwable $e): Response
    {
        //id不存在
        if ($e instanceof ModelNotFoundException)
        {
            return $this->returnJson('THE ID DATA NotFound', $e->getCode());
        }

        //验证器异常
        if ($e instanceof ValidateException)
        {
            return $this->returnJson($e->getMessage(),$e->getCode());
        }

        //服务异常
        if ($e instanceof ServiceException)
        {
            return $this->returnJson($e->getMessage(), $e->getCode());
        }

        //参数异常
        if ($e instanceof ParamException)
        {
            return $this->returnJson($e->getMessage(), $e->getCode());
        }

        //权限异常
        if ($e instanceof AuthException)
        {
            return $this->returnJson($e->getMessage(), $e->getCode());
        }

        if ($e instanceof RouteNotFoundException)
        {
//            return abort(404, "路由未定义或不匹配");
            return $this->returnJson("路由未定义或不匹配", $e->getCode(), 404);
        }

        //外部服务异常
        if ($e instanceof OutsideApiException)
        {
            return $this->returnJson('outsideApi,'.$e->getMessage(), $e->getCode());
        }

        if ($e instanceof ConfigurationException)
        {
            return $this->returnJson($e->getMessage(), $e->getCode());
        }

        // 其他错误交给系统处理
        return parent::render($request, $e);
    }
}